package main

import (
	"crypto/tls"
	"fmt"
	"github.com/go-ldap/ldap/v3"
	"log"
	"strings"
)

func main() {
	config := &tls.Config{InsecureSkipVerify: true}
	l, err := ldap.DialURL("ldap://101.34.5.144:389", ldap.DialWithTLSConfig(config))
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	_, err = l.SimpleBind(&ldap.SimpleBindRequest{
		Username: "cn=jack,ou=People,dc=demo,dc=com",
		Password: "123456",
	})
	if err != nil {
		log.Fatalf("Failed to bind: %s\n", err)
	}

	//err = l.Bind("jack@demo.com", "123456")
	//if err != nil {
	//	log.Fatalf("bind user err: %s\n", err)
	//}

	searchString := fmt.Sprintf("(&(objectClass=person)(cn=%s))", "jack")
	memberSearchAttribute := "memberOf"

	//searchRequest := ldap.NewSearchRequest(
	//	"dc=demo,dc=com", // The base dn to search
	//	ldap.ScopeWholeSubtree,
	//	ldap.NeverDerefAliases,
	//	0,
	//	0,
	//	false,
	//	fmt.Sprintf("(&(objectClass=person)(cn=%s))", "jack"), // The filter to apply
	//	[]string{"memberOf"}, // A list attributes to retrieve
	//	nil,
	//)

	searchRequest := ldap.NewSearchRequest(
		"dc=demo,dc=com",
		ldap.ScopeWholeSubtree,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		searchString,
		[]string{memberSearchAttribute},
		nil,
	)

	sr, err := l.Search(searchRequest)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(sr)
	//fmt.Println(len(sr.Entries))
	entry := sr.Entries[0]
	for _, e := range entry.Attributes {
		fmt.Println(e.Values)
		for _, attr := range e.Values {
			fmt.Println(attr)
			groupList := strings.Split(attr, ",")
			for _, g := range groupList {
				if strings.HasPrefix(g, "cn=") {
					group := strings.Split(g, "=")
					fmt.Println(group)
				}
			}
		}
	}

}
